import _slicedToArray from '@babel/runtime/helpers/esm/slicedToArray';
import _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray';
import { useRef, useState } from 'react';
var useList = function useList(opts) {
  var _ref = opts || {},
    _ref$initialDataSourc = _ref.initialDataSource,
    initialDataSource = _ref$initialDataSourc === void 0 ? [{}] : _ref$initialDataSourc,
    onChange = _ref.onChange,
    onAddOrRemove = _ref.onAddOrRemove;
  var _useState = useState(initialDataSource),
    _useState2 = _slicedToArray(_useState, 2),
    dataSource = _useState2[0],
    setDataSource = _useState2[1];
  var countRef = useRef(0);
  var add = function add(item) {
    dataSource.push(item || {});
    changeDataSource(_toConsumableArray(dataSource));
    onAddOrRemove && onAddOrRemove();
  };
  var remove = function remove(item) {
    countRef.current = countRef.current + 1;
    if (typeof item === 'number') {
      dataSource.splice(item, 1);
      changeDataSource(_toConsumableArray(dataSource));
    } else {
      var newDataSource = dataSource.filter(function (it) {
        return item !== it;
      });
      changeDataSource(newDataSource);
    }
    onAddOrRemove && onAddOrRemove();
  };
  var changeDataSource = function changeDataSource(newDataSource) {
    setDataSource(newDataSource);
    onChange && onChange(newDataSource);
  };
  return {
    dataSource: dataSource,
    setDataSource: changeDataSource,
    add: add,
    remove: remove,
    mainKey: countRef.current,
  };
};
export default useList;
